//
//  ViewController.m
//  MapGenerator
//
//  Created by zg.shao on 15/2/13.
//  Copyright (c) 2015年 kuwo.cn. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () {
    UIView *_padView;
    NSArray *_keyLabelList;
    
    UIView *_controlView;
    
    NSInteger _curLevelIndex;
    NSMutableArray *_allGameLevels; // 从plist中读取到内存中，考虑到数据量不是很大，直接一次读取完毕吧。
    UILabel *_titleLabel;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self readGameLevelFromPlist];
    
    [self initPadSubViews];
    
    [self initControlSubViews];
    
    [self updateCellValues];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)readGameLevelFromPlist {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath1 = [paths objectAtIndex:0];
    
    //得到完整的文件名
    NSString *filename = [plistPath1 stringByAppendingPathComponent:@"test.plist"];
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"level" ofType:@"plist"];
    _allGameLevels = [NSMutableArray arrayWithContentsOfFile:filename];
    
    NSLog(@"filename:%@", filename);
    _curLevelIndex = [_allGameLevels count] - 1;
}

- (void)saveGameLevelToPlist {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *plistPath1 = [paths objectAtIndex:0];
    
    //得到完整的文件名
    NSString *filename = [plistPath1 stringByAppendingPathComponent:@"test.plist"];
    [_allGameLevels writeToFile:filename atomically:YES];
}

- (void)updateCellValues {
    [_titleLabel setText:[NSString stringWithFormat:@"%d", _curLevelIndex]];
    
    if (_curLevelIndex == [_allGameLevels count] && _curLevelIndex > 0) {
        NSMutableDictionary *mutabDict = [[NSMutableDictionary alloc] init];
        [_allGameLevels addObject:mutabDict];
    }
    
    NSDictionary *dict = [_allGameLevels objectAtIndex:_curLevelIndex];
    for (UIButton *padBtn in _keyLabelList) {
        [padBtn setTitle:@"" forState:UIControlStateNormal];
    }
    
    for (NSString *key in [dict allKeys]) {
        if ([key isEqualToString:@"tip"]) {
            continue;
        }
        NSInteger index = [key integerValue];
        NSInteger value = [[dict objectForKey:key] integerValue];
        
        UIButton *btn = [_keyLabelList objectAtIndex:index];
        [[_keyLabelList objectAtIndex:index] setTitle:[NSString stringWithFormat:@"%d", value] forState:UIControlStateNormal];
    }
}

- (void)initPadSubViews {
    _padView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
    
    const NSInteger nSpaceWidth = 2;
    const NSInteger nCellWidth = (SCREEN_WIDTH - nSpaceWidth * 4) / 5;
    const NSInteger nCellHeight = (SCREEN_WIDTH - nSpaceWidth * 5) / 6;
    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:30];
    for (int i = 0; i < 6; i ++) {
        for (int j = 0; j < 5; j ++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            btn.selected = NO;
            btn.tag = GET_INDEX(i, j);

            [btn.titleLabel setFont:[UIFont systemFontOfSize:35]];
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            [btn setBackgroundColor:[UIColor lightGrayColor]];
            
            [btn setFrame:CGRectMake(j * (nSpaceWidth + nCellWidth), i * (nSpaceWidth + nCellHeight), nCellWidth, nCellHeight)];
            [_padView addSubview:btn];
            
            [array addObject:btn];
        }
    }
    
    _keyLabelList = [array copy];
    [self.view addSubview:_padView];
}

- (void)btnClick:(UIButton *)btn {
    NSInteger tag = btn.tag;
    NSLog(@"y:%d,x=%d", GET_ROW_INDEX(tag), GET_COL_INDEX(tag));
    
    [self setBtnSelect:btn];
}

- (void)setBtnSelect:(UIButton *)btn {
    for (UIButton *tmpBtn in _keyLabelList) {
        tmpBtn.selected = NO;
    }
    
    if (btn) {
        btn.selected = YES;
    }
}

- (void)initControlSubViews {
    _controlView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH, SCREEN_WIDTH, SCREEN_HEIGHT - SCREEN_WIDTH)];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _controlView.bounds.size.width * 3 / 5, _controlView.bounds.size.height)];
    [leftView setBackgroundColor:[UIColor blackColor]];
    [_controlView addSubview:leftView];
    
    const NSInteger nSpaceSize = 1;
    NSInteger nCellWidth = (leftView.bounds.size.width - 5) / 6;
    NSInteger nCellHeight = (leftView.bounds.size.height - 2) / 3;
    for (int i = 0; i < 3; i ++) {
        for (int j = 0; j < 6; j ++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            [btn setBackgroundColor:[UIColor colorWithRed:246 green:246 blue:246 alpha:1]];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            if (i * 6 + j == 17) {
                [btn setTitle:@"24678" forState:UIControlStateNormal];
                btn.tag = 24678;
            } else if (i * i + j * j == 0) {
                [btn setTitle:@"清空" forState:UIControlStateNormal];
                btn.tag = 0;
            } else if (i * 6 + j == 16) {
                [btn setTitle:@"0" forState:UIControlStateNormal];
                btn.tag = 16;
            } else {
                [btn setTitle:[NSString stringWithFormat:@"%d", i * 6 + j] forState:UIControlStateNormal];
                btn.tag = i * 6 + j;
            }
            [btn.titleLabel setFont:[UIFont systemFontOfSize:26]];
            
            [btn setFrame:CGRectMake(j * (nCellWidth + nSpaceSize), i * (nCellHeight + nSpaceSize), nCellWidth, nCellHeight)];
            [btn addTarget:self action:@selector(setNumberBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [leftView addSubview:btn];
        }
    }
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(leftView.bounds.size.width, 0, _controlView.bounds.size.width - leftView.bounds.size.width, _controlView.bounds.size.height)];
    [rightView setBackgroundColor:[UIColor blackColor]];
    [_controlView addSubview:rightView];
    
    nCellWidth = (rightView.bounds.size.width - 1) / 2;
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, rightView.bounds.size.width, nCellHeight)];
    [_titleLabel setBackgroundColor:[UIColor whiteColor]];
    [_titleLabel setTextColor:[UIColor blueColor]];
    [_titleLabel setTextAlignment:NSTextAlignmentCenter];
    [_titleLabel setFont:[UIFont systemFontOfSize:25]];
    [rightView addSubview:_titleLabel];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [leftBtn setTitle:@"上一关" forState:UIControlStateNormal];
    [leftBtn setBackgroundColor:[UIColor whiteColor]];
    [leftBtn addTarget:self action:@selector(preLevelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [leftBtn setFrame:CGRectMake(0, nCellHeight + 1, nCellWidth, nCellHeight)];
    [rightView addSubview:leftBtn];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [rightBtn setTitle:@"下一关" forState:UIControlStateNormal];
    [rightBtn setBackgroundColor:[UIColor whiteColor]];
    [rightBtn addTarget:self action:@selector(nextLevelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setFrame:CGRectMake(nCellWidth + 1, nCellHeight + 1, nCellWidth, nCellHeight)];
    [rightView addSubview:rightBtn];
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setBackgroundColor:[UIColor whiteColor]];
    [saveBtn addTarget:self action:@selector(saveLevelInfoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setFrame:CGRectMake(0, nCellHeight * 2 + 2, rightView.bounds.size.width, nCellHeight)];
    [rightView addSubview:saveBtn];
    
    [self.view addSubview:_controlView];
}

- (void)setNumberBtnClick:(UIButton *)btn {
    NSInteger tag = btn.tag;
    if (tag == 0) {
        for (UIButton *padBtn in _keyLabelList) {
            [padBtn setTitle:@"" forState:UIControlStateNormal];
        }
        
        return ;
    }
    
    for (UIButton *padBtn in _keyLabelList) {
        if (padBtn.selected) {
            if (tag == 17) {
                [padBtn setTitle:@"24678" forState:UIControlStateNormal];
            } else if (tag == 16) {
                [padBtn setTitle:@"0" forState:UIControlStateNormal];
            } else {
                [padBtn setTitle:[NSString stringWithFormat:@"%d", tag] forState:UIControlStateNormal];
            }
            
            break;
        }
    }
}

- (void)preLevelBtnClick:(UIButton *)sender {
    NSLog(@"----curLevelIndex1111:%d", _curLevelIndex-1);
    if (_curLevelIndex - 1 >= 0) {
        _curLevelIndex -= 1;
        
        [self updateCellValues];
    }
}

- (void)nextLevelBtnClick:(UIButton *)sender {
    NSLog(@"----curLevelIndex222:%d", _curLevelIndex + 1);
    if (_curLevelIndex >= [_allGameLevels count]) {
        NSMutableDictionary *subDict = [[NSMutableDictionary alloc] init];
        [_allGameLevels addObject:subDict];
    }
    
    NSMutableDictionary *dict = [_allGameLevels objectAtIndex:_curLevelIndex];
    [dict removeAllObjects];
    for (int i = 0; i < 30; i ++) {
        UIButton *btn = [_keyLabelList objectAtIndex:i];
        if ([[btn currentTitle] length] > 0) {
            NSInteger value = [[btn currentTitle] integerValue];
            [dict setObject:[NSNumber numberWithInteger:value] forKey:[NSString stringWithFormat:@"%d", i]];
        }
    }
    
    _curLevelIndex += 1;
    
    [self updateCellValues];
}

- (void)saveLevelInfoBtnClick:(UIButton *)sender {
    NSMutableDictionary *dict = [_allGameLevels objectAtIndex:_curLevelIndex];
    for (int i = 0; i < 30; i ++) {
        UIButton *btn = [_keyLabelList objectAtIndex:i];
        if ([[btn currentTitle] length] > 0) {
            NSInteger value = [[btn currentTitle] integerValue];
            [dict setObject:[NSNumber numberWithInteger:value] forKey:[NSString stringWithFormat:@"%d", i]];
        }
    }
    
    [self saveGameLevelToPlist];
}
@end
